﻿using DTcms.Common;
using DTcms.Model;
using DTcms.Web.Mvc.UI;
using System;
using System.Collections.Generic;
using System.Data;
using System.Text;
using System.Web.Mvc;

namespace DTcms.Web.Mvc.Areas.Admin.Controllers
{
    public class ArticleController : ManageController
    {
        protected BaseApi _service = new BaseApi();
        protected int totalCount = 0;
        protected Model.manager managerModel = new Model.manager();
        protected string _action;
        protected int _id;
        protected int _channel_id;

        private string curAuthString;//权限字符串
        protected Model.site_channel chlmodel;//定义频道实体类
        protected Model.manager_role roleModel;//管理员角色实体类
        protected override void OnAuthorization(AuthorizationContext filterContext)
        {
            base.OnAuthorization(filterContext);
            ActionResult result = View(EDIT_RESULT_VIEW);
            managerModel = GetAdminInfo();
            _action = DTRequest.GetQueryString("action");
            _id = DTRequest.GetQueryInt("id");
            _channel_id = DTRequest.GetQueryInt("channel_id");
            ViewBag.action = _action;
            ViewBag.id = _id;
            ViewBag.channel_id = _channel_id;
            if (_channel_id > 0)
            {
                this.chlmodel = new BLL.site_channel().GetModel(this._channel_id);
                if (this.chlmodel == null)
                {
                    ViewBag.ClientScript = JscriptMsg("频道不存在！", "back");
                    filterContext.Result = result;
                    return;
                }
            }
        }

        #region 页面创建
        public ActionResult Article_List()
        {
            this.curAuthString = string.Format("channel_{0}_list", this.chlmodel.name);
            ChkAdminLevel(this.curAuthString, DTEnums.ActionEnum.View.ToString(), out roleModel); //检查权限
            string prolistview2 = Utils.GetCookie("article_list_view_" + this.chlmodel.name);
            string prolistview = string.Empty;
            if (string.IsNullOrEmpty(prolistview2))
            {
                if (this.chlmodel.is_type > 0)
                {
                    prolistview = "Txt";
                }
                else
                {
                    prolistview = "Img";
                }
            }
            else
            {
                if (string.IsNullOrEmpty(prolistview))
                {
                    prolistview = prolistview2;
                }
            }
            ViewBag.ProListView = prolistview;

            //条件
            IList<int> catlist = new List<int>();
            var category = _service.CategoryTreeBind(_channel_id, out catlist);
            List<SelectListItem> moveListItems = new List<SelectListItem>() {
                new SelectListItem(){ Text="批量移动...", Value=""}
            };
            moveListItems.AddRange(category);
            ViewBag.moveListItems = moveListItems;
            return View();
        }
        public ActionResult Category_List()
        {
            this.curAuthString = string.Format("channel_{0}_category", this.chlmodel.name);
            ChkAdminLevel(this.curAuthString, DTEnums.ActionEnum.View.ToString(), out roleModel); //检查权限
            return View();
        }
        public JsonResult categoryList()
        {
            DataTable ds = _service.CategoryBind(_channel_id);
            return Json(new { code = 0, msg = "", data = ds, count = 0 });
        }
        public ActionResult Comment_List()
        {
            this.curAuthString = string.Format("channel_{0}_comment", this.chlmodel.name);
            ChkAdminLevel(this.curAuthString, DTEnums.ActionEnum.View.ToString(), out roleModel); //检查权限
            return View();
        }
        public ActionResult Recycle_List()
        {
            this.curAuthString = string.Format("channel_{0}_recycle", this.chlmodel.name);
            ChkAdminLevel(this.curAuthString, DTEnums.ActionEnum.View.ToString(), out roleModel); //检查权限
            return View();
        }

        public ActionResult Comment_Edit()
        {
            Model.article_comment model = new Model.article_comment();
            if (_id == 0)
            {
                return ResultMsg("传输参数不正确！", "back");
            }
            model = _service.CommentInfo(_id);
            if (model == null)
            {
                return ResultMsg("记录不存在或已被删除！", "back");
            }
            return View(model);
        }
        public ActionResult Category_Edit()
        {
            //浏览权限
            ChkAdminLevel("channel_" + this.chlmodel.name + "_category", DTEnums.ActionEnum.View.ToString());
            Model.article_category model = new Model.article_category();
            if (!string.IsNullOrEmpty(_action) && _action == DTEnums.ActionEnum.Edit.ToString())
            {
                if (_id == 0)
                {
                    return ResultMsg("传输参数不正确！", "back");
                }
                model = _service.CategoryInfo(_id);
                if (model == null)
                {
                    return ResultMsg("记录不存在或已被删除！", "back");
                }
            }
            else
            {
                if (_id > 0)
                {
                    model.parent_id = _id;
                }
            }
            ViewBag.channelModel = chlmodel;
            return View(model);
        }
        public ActionResult Article_Edit()
        {
            ChkAdminLevel("channel_" + this.chlmodel.name + "_list", DTEnums.ActionEnum.View.ToString()); //检查权限
            Model.article model = new Model.article();
            //如果是编辑或复制则检查信息是否存在
            if (_action == DTEnums.ActionEnum.Edit.ToString() || _action == DTEnums.ActionEnum.Copy.ToString())
            {
                if (_id == 0)
                {
                    return ResultMsg("传输参数不正确！", "back");
                }
                model = _service.ArticleInfo(_id, _channel_id);
                if (model == null)
                {
                    return ResultMsg("信息不存在或已被删除！", "back");
                }
            }
            else
            {
                model.sort_id = 99;
                model.add_time = DateTime.Now;
                model.img_url = "";
                ViewBag.GoodsSpecJson = "";
            }
            ViewBag.siteConfig = siteConfig;
            ViewBag.channelModel = chlmodel;
            ViewBag.otherFieldList = _service.CreateOtherField(this._channel_id); //动态生成相应的扩展字段
            ViewBag.sysFieldList = _service.ShowSysField(this._channel_id);
            return View(model);
        }
        #endregion

        #region 还原
        #region 组合SQL查询语句
        protected string RecycleCombSqlTxt(string _keywords, string _property)
        {
            StringBuilder strTemp = new StringBuilder();
            _keywords = _keywords.Replace("'", "");
            if (!string.IsNullOrEmpty(_keywords))
            {
                strTemp.Append(" and title like '%" + _keywords + "%'");
            }
            if (!string.IsNullOrEmpty(_property))
            {
                switch (_property)
                {
                    case "isMsg":
                        strTemp.Append(" and is_msg=1");
                        break;
                    case "isTop":
                        strTemp.Append(" and is_top=1");
                        break;
                    case "isRed":
                        strTemp.Append(" and is_red=1");
                        break;
                    case "isHot":
                        strTemp.Append(" and is_hot=1");
                        break;
                    case "isSlide":
                        strTemp.Append(" and is_slide=1");
                        break;
                }
            }
            return strTemp.ToString();
        }
        #endregion

        #region 数据绑定
        public JsonResult RecycleList(int channel_id = 0, int category_id = 0, string keywords = "", string property = "", int page = 1, int limit = 10)
        {
            string return_term = string.Empty;
            if (!string.IsNullOrEmpty(return_term))
            {
                return_term = "status=2 and category_id in (" + return_term + ")";
            }
            else
            {
                return_term = "status=2";
            }

            string strWhere = return_term + RecycleCombSqlTxt(keywords, property);
            string strOrder = "sort_id asc,add_time desc,id desc";
            DataTable resultList = _service.ArticleBind(channel_id, category_id, strWhere, strOrder, out totalCount, page, limit);
            DataTable oldData = resultList.Clone();
            if (resultList.Rows.Count > 0)
            {
                oldData.Columns.Add("categoryTitle", Type.GetType("System.String"));
                foreach (DataRow item in resultList.Rows)
                {
                    DataRow row = oldData.NewRow();
                    string link_url = item["link_url"].ToString();
                    row["title"] = item["title"];
                    row["category_id"] = item["category_id"];
                    row["call_index"] = item["call_index"].ToString();
                    row["add_time"] = item["add_time"];
                    row["sort_id"] = item["sort_id"];
                    row["status"] = item["status"];
                    row["is_msg"] = item["is_msg"];
                    row["id"] = item["id"];
                    row["img_url"] = item["img_url"].ToString();
                    row["zhaiyao"] = item["zhaiyao"].ToString();
                    row["is_top"] = item["is_top"];
                    row["is_red"] = item["is_red"];
                    row["is_hot"] = item["is_hot"];
                    row["is_slide"] = item["is_slide"];
                    if (string.IsNullOrEmpty(link_url))
                    {
                        link_url = UrlHelperExtend.get_url_rewrite(chlmodel.name, "detail", item["call_index"].ToString(), Utils.StrToInt(item["id"].ToString(), 0));
                    }
                    row["link_url"] = link_url;
                    row["categoryTitle"] = new BLL.article_category().GetTitle(Utils.ObjToInt(item["category_id"]));
                    oldData.Rows.Add(row);
                }
            }
            #region 清除不必要的字段
            if (resultList.Rows.Count > 0)
            {
                //resultList.Columns.Remove("content");
            }
            #endregion
            return Json(new { status = 1, msg = "", item = oldData, totalCount = totalCount });
        }
        #endregion

        #region 删除
        public JsonResult RecycleDelete(int channel_id, List<int> ids)
        {
            return _service.RecycleDelete(channel_id, ids);
        }
        #endregion

        #region 还原
        public JsonResult RecycleAudit(int channel_id, List<int> ids)
        {
            return _service.RecycleAudit(channel_id, ids);
        }
        #endregion
        #endregion

        #region 评论
        #region 组合SQL查询语句
        protected string CommentSqlTxt(string _keywords, string _property)
        {
            StringBuilder strTemp = new StringBuilder();
            _keywords = _keywords.Replace("'", "");
            if (!string.IsNullOrEmpty(_keywords))
            {
                strTemp.Append(" and (user_name like '%" + _keywords + "%' or content like '%" + _keywords + "%')");
            }
            if (!string.IsNullOrEmpty(_property))
            {
                switch (_property)
                {
                    case "isLock":
                        strTemp.Append(" and is_lock=1");
                        break;
                    case "unLock":
                        strTemp.Append(" and is_lock=0");
                        break;
                }
            }
            return strTemp.ToString();
        }
        #endregion

        #region 数据绑定
        public JsonResult CommentList(int channel_id = 0, string keywords = "", string property = "", int page = 1, int limit = 10)
        {
            string strWhere = "channel_id=" + channel_id + CommentSqlTxt(keywords, property);
            string strOrder = "add_time desc";
            var resultList = _service.CommentBind(strWhere, strOrder, page, limit);
            DataTable Items = DataHelper.ListToDataTable(resultList.Items);
            DataTable oldData = Items.Clone();
            if (resultList.TotalItems > 0)
            {
                oldData.Columns.Add("ArticleTitle", Type.GetType("System.String"));
                foreach (DataRow item in Items.Rows)
                {
                    DataRow row = oldData.NewRow();
                    row["user_name"] = item["user_name"];
                    row["add_time"] = item["add_time"];
                    row["is_lock"] = item["is_lock"];
                    row["content"] = Utils.ToTxt(item["content"].ToString());
                    row["is_reply"] = item["is_reply"];
                    row["reply_content"] = item["reply_content"];
                    row["reply_time"] = item["reply_time"];
                    row["id"] = item["id"];
                    row["ArticleTitle"] = new BLL.article().GetTitle(Utils.ObjToInt(item["channel_id"]), Utils.ObjToInt(item["article_id"]));
                    oldData.Rows.Add(row);
                }
            }
            return Json(new { status = 1, msg = "", item = oldData, totalCount = resultList.TotalItems });
        }
        #endregion

        #region 删除
        public JsonResult CommentDelete(int channel_id, List<int> ids)
        {
            return _service.CommentDelete(channel_id, ids);
        }
        #endregion

        #region 审核
        public JsonResult CommentAudit(int channel_id, List<int> ids)
        {
            return _service.CommentAudit(channel_id, ids);
        }
        #endregion

        #region 保存
        [HttpPost, ValidateInput(false), CustomValidateAntiForgeryToken]
        public ActionResult CommentSave(Model.article_comment t)
        {
            SaveModel save = _service.CommentSave(_id, t);
            save.url = save.status == 0 ? "back" : "../article/comment_list?channel_id=" + _channel_id;
            return Json(save);
        }
        #endregion
        #endregion

        #region 内容类别
        [HttpPost, ValidateInput(false), CustomValidateAntiForgeryToken]
        public ActionResult CategorySave(Model.article_category t)
        {
            t.site_id = chlmodel.site_id;
            SaveModel save = _service.CategorySave(_action, _id, _channel_id, t);
            save.url = save.status == 0 ? "back" : "../article/category_list?channel_id=" + _channel_id;
            return Json(save);
        }
        [HttpPost]
        public JsonResult CategoryLock(int id, bool is_lock)
        {
            ChkAdminLevel("channel_" + chlmodel.name + "_category", DTEnums.ActionEnum.Edit.ToString()); //检查权限
            BLL.article_category bll = new BLL.article_category();
            if (bll.UpdateFile("id=" + id, "is_lock=" + (is_lock ? 0 : 1)))
            {
                return Json(new { status = 1, msg = "状态修改成功！" });
            }
            return Json(new { status = 0, msg = "状态修改失败！" });
        }

        [HttpPost]
        public JsonResult CategoryDelete(List<int> ids)
        {
            return _service.CategoryDelete(_channel_id, ids);
        }

        [HttpPost]
        public JsonResult CategorySort(string field, string value, int id = 0)
        {
            if (string.IsNullOrEmpty(field) || id == 0)
            {
                return Json(new { status = 0, msg = "参数错误！" });
            }
            string channel_name = new BLL.site_channel().GetChannelName(_channel_id); //取得频道名称
            ChkAdminLevel("channel_" + channel_name + "_category", DTEnums.ActionEnum.Edit.ToString()); //检查权限
            BLL.article_category bll = new BLL.article_category();
            if (bll.UpdateFile("id=" + id, field + "=" + value))
            {
                AddAdminLog(DTEnums.ActionEnum.Edit.ToString(), "保存" + channel_name + "频道栏目分类排序"); //记录日志
                return Json(new { status = 1, msg = "修改成功！" });
            }
            return Json(new { status = 0, msg = "修改失败！" });
        }
        #endregion

        #region 内容列表
        #region 组合SQL查询语句==========================
        protected string ArticleCombSqlTxt(string _keywords, string _property)
        {
            StringBuilder strTemp = new StringBuilder();
            if (!string.IsNullOrEmpty(_keywords))
            {
                _keywords = _keywords.Replace("'", "");
                strTemp.Append(" and title like '%" + _keywords + "%'");
            }
            if (!string.IsNullOrEmpty(_property))
            {
                switch (_property)
                {
                    case "isLock":
                        strTemp.Append(" and status=1");
                        break;
                    case "unIsLock":
                        strTemp.Append(" and status=0");
                        break;
                    case "isMsg":
                        strTemp.Append(" and is_msg=1");
                        break;
                    case "isTop":
                        strTemp.Append(" and is_top=1");
                        break;
                    case "isRed":
                        strTemp.Append(" and is_red=1");
                        break;
                    case "isHot":
                        strTemp.Append(" and is_hot=1");
                        break;
                    case "isSlide":
                        strTemp.Append(" and is_slide=1");
                        break;
                }
            }
            return strTemp.ToString();
        }
        #endregion
        public JsonResult ArticleList(string keywords, int channel_id, string property, int isGrid = 0, int category_id = 0, int page = 1, int limit = 10)
        {
            //条件
            IList<int> catlist = new List<int>();
            _service.CategoryTreeBind(channel_id, out catlist);
            string strWhere = "status<2";
            if (catlist.Count > 0)
            {
                strWhere += " and category_id in (" + string.Join(",", catlist) + ")";
            }
            string strOrder = "sort_id asc,add_time desc,id desc";
            DataTable resultList = _service.ArticleBind(channel_id, category_id, strWhere + ArticleCombSqlTxt(keywords, property), strOrder, out totalCount, page, limit);
            DataTable oldData = new DataTable();
            oldData.Columns.Add("id", Type.GetType("System.Int32"));
            oldData.Columns.Add("title", Type.GetType("System.String"));
            oldData.Columns.Add("category_id", Type.GetType("System.Int32"));
            oldData.Columns.Add("call_index", Type.GetType("System.String"));
            oldData.Columns.Add("add_time", Type.GetType("System.String"));
            oldData.Columns.Add("sort_id", Type.GetType("System.Int32"));
            oldData.Columns.Add("status", Type.GetType("System.Int32"));
            oldData.Columns.Add("is_msg", Type.GetType("System.Int32"));
            oldData.Columns.Add("img_url", Type.GetType("System.String"));
            oldData.Columns.Add("zhaiyao", Type.GetType("System.String"));
            oldData.Columns.Add("is_top", Type.GetType("System.Int32"));
            oldData.Columns.Add("is_red", Type.GetType("System.Int32"));
            oldData.Columns.Add("is_hot", Type.GetType("System.Int32"));
            oldData.Columns.Add("is_slide", Type.GetType("System.Int32"));
            oldData.Columns.Add("link_url", Type.GetType("System.String"));
            oldData.Columns.Add("CategoryTitle", Type.GetType("System.String"));
            if (resultList.Rows.Count > 0)
            {
                foreach (DataRow item in resultList.Rows)
                {
                    DataRow row = oldData.NewRow();
                    string link_url = item["link_url"].ToString();
                    row["title"] = item["title"];
                    row["category_id"] = item["category_id"];
                    row["call_index"] = item["call_index"].ToString();
                    row["add_time"] = item["add_time"];
                    row["sort_id"] = item["sort_id"];
                    row["status"] = item["status"];
                    row["is_msg"] = item["is_msg"];
                    row["id"] = item["id"];
                    row["img_url"] = item["img_url"].ToString();
                    row["zhaiyao"] = item["zhaiyao"].ToString();
                    row["is_top"] = item["is_top"];
                    row["is_red"] = item["is_red"];
                    row["is_hot"] = item["is_hot"];
                    row["is_slide"] = item["is_slide"];
                    if (string.IsNullOrEmpty(link_url))
                    {
                        link_url = UrlHelperExtend.get_url_rewrite(chlmodel.name, "detail", item["call_index"].ToString(), Utils.StrToInt(item["id"].ToString(), 0));
                    }
                    row["link_url"] = link_url;
                    row["CategoryTitle"] = new BLL.article_category().GetTitle(Utils.ObjToInt(item["category_id"]));
                    oldData.Rows.Add(row);
                }
            }
            if (isGrid == 1)
            {
                return Json(new { code = 0, msg = "", data = oldData, count = totalCount });
            }
            else
            {
                return Json(new { status = 1, msg = "", item = oldData, totalCount = totalCount });
            }
        }

        #region 审核
        [HttpPost]
        public JsonResult ArticleAudit(List<int> ids)
        {
            return _service.ArticleAudit(_channel_id, ids);
        }
        #endregion
        #region 回收站
        [HttpPost]
        public JsonResult ArticleRecycle(List<int> ids)
        {
            return _service.ArticleRecycle(_channel_id, ids);
        }
        #endregion
        #region 彻底删除
        [HttpPost]
        public JsonResult ArticleDelete(List<int> ids)
        {
            return _service.ArticleDelete(_channel_id, ids);
        }
        #endregion
        #region 微信推送  待完成
        [HttpPost]
        public JsonResult ArticleWx(List<int> ids, int accountId = 0)
        {
            return _service.ArticleWxPost(_channel_id, ids, accountId);
        }
        #endregion
        #region 批量移动
        [HttpPost]
        public JsonResult ArticleMove(List<int> ids, int category_id = 0)
        {
            return _service.ArticleMove(_channel_id, ids, category_id);
        }
        #endregion
        #region 字段修改
        [HttpPost]
        public JsonResult ArticleFiledSave(string field, int value, int id = 0)
        {
            ChkAdminLevel("channel_" + chlmodel.name + "_list", DTEnums.ActionEnum.Edit.ToString()); //检查权限
            if (string.IsNullOrEmpty(field) || id == 0)
            {
                return Json(new { status = 0, msg = "参数错误！" });
            }
            BLL.article bll = new BLL.article();
            if (bll.UpdateField(_channel_id, id, field + "=" + value))
            {
                return Json(new { status = 1, msg = "修改成功！" });
            }
            return Json(new { status = 0, msg = "修改失败！" });
        }
        #endregion
        #region 设置列表显示
        [HttpPost]
        public JsonResult ArticleView(string view)
        {
            if (string.IsNullOrEmpty(view))
            {
                return Json(new { status = 0, msg = "关键参数未传递！" });
            }
            Utils.WriteCookie("article_list_view_" + chlmodel.name, view, 14400);
            return Json(new { status = 1, msg = "设置列表显示成功！" });
        }
        #endregion
        #region 设置状态
        [HttpPost]
        public JsonResult ArticleSwitch(int id, bool status)
        {
            ChkAdminLevel("channel_" + chlmodel.name + "_list", DTEnums.ActionEnum.Edit.ToString()); //检查权限
            BLL.article bll = new BLL.article();
            if (bll.UpdateField(_channel_id, id, "status=" + (status ? 0 : 1)))
            {
                return Json(new { status = 1, msg = "设置状态成功！" });
            }
            return Json(new { status = 0, msg = "设置状态失败！" });
        }
        #endregion
        #region 个别字段修改
        [HttpPost]
        public JsonResult TagsFiledSave(string field, int value, int id = 0)
        {
            ChkAdminLevel("channel_" + chlmodel.name + "_list", DTEnums.ActionEnum.Edit.ToString()); //检查权限
            if (string.IsNullOrEmpty(field) || id == 0)
            {
                return Json(new { status = 0, msg = "参数错误！" });
            }
            BLL.article bll = new BLL.article();
            if (bll.UpdateField(_channel_id, id, field + "=" + value))
            {
                return Json(new { status = 1, msg = "修改成功！" });
            }
            return Json(new { status = 0, msg = "修改失败！" });
        }
        #endregion
        #region 保存
        [HttpPost, ValidateInput(false), CustomValidateAntiForgeryToken]
        public ActionResult ArticleSave(Model.article t)
        {
            SaveModel save = _service.ArticleSave(_action, _id, _channel_id, t);
            save.url = save.status == 0 ? "back" : "../article/article_list?channel_id=" + _channel_id;
            return Json(save);
        }
        #endregion

        [HttpPost]
        public JsonResult ArticleStatus(int id, string cmdName)
        {
            return _service.ArticleStatus(_channel_id, id, cmdName);
        }
        #endregion

        #region 规格管理
        public ActionResult Spec_List()
        {
            this.curAuthString = string.Format("channel_{0}_spec", this.chlmodel.name);
            ChkAdminLevel(this.curAuthString, DTEnums.ActionEnum.View.ToString(), out roleModel); //检查权限
            return View();
        }
        #endregion
    }
}
